import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  // token: getToken(),
  name: '', // userNickName:'',
  avatar: '',
  // introduction: '',
  // roles: window.sessionStorage.getItem('roles')||[],//roleName:'',
  roles: [], // roleName:'',

  // 用户自定义state
  userId: '',
  titlePic: ''

}

const mutations = {
  SET_TOKEN: (state, token) => {
    console.log('Set Token')
    state.token = token
    console.log(state.token)
  },
  // SET_INTRODUCTION: (state, introduction) => {
  //   state.introduction = introduction
  // },
  SET_NAME: (state, userNickName) => {
    state.name = userNickName
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, role) => {
    state.roles.push(role)
  },
  SET_ROLESClear: (state) => {
    state.roles = []
  },

  //  用户自定义state
  SET_ID: (state, id) => {
    state.userId = id
  },
  SET_titlePic: (state, titlePic) => {
    state.titlePic = titlePic
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, isRememberMe } = userInfo
    return new Promise((resolve, reject) => {
      login({ UserName: username.trim(), Password: password, IsRememberMe: isRememberMe }).then(response => {
        const { data } = response
        // console.log(data);
        // console.log(data.token);

        commit('SET_TOKEN', data.token)// 将token存在state中
        // window.sessionStorage.setItem('token',data.token);
        commit('SET_ID', data.userId)// 将userId存在state中
        // commit('SET_ROLES', data.roleName)//将userId存在state中

        // setToken(data.token)//将token存在cookie中
        // ？？？

        // 更新信息于cookies中
        // 此时留一个问题，登录时记住我应该怎么体现在程序中
        if (isRememberMe) {
          setToken(data.token)// 将token存在cookie中
        }
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.userId).then(response => {
        // console.log(state.userId);
        const { data } = response
        console.log('getUserInfo')
        console.log(data)

        if (!data) {
          reject('登录身份已过期，请重新登录')
        }

        const { name, nickName, roleName, titlePic } = data

        // roles must be a non-empty array
        if (!roleName || roleName === '') {
          reject('getInfo: 角色不能为空!')
        }

        commit('SET_ROLES', roleName)
        // window.sessionStorage.setItem('roles',state.roles)
        commit('SET_NAME', nickName)
        commit('SET_titlePic', titlePic)
        // commit('SET_AVATAR', avatar)
        // commit('SET_INTRODUCTION', introduction)

        resolve(data)
      }).catch(error => {
        console.log(state.token)
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout().then((res) => {
      //  console.log(res);
        commit('SET_TOKEN', '')
        commit('SET_ROLESClear')
        commit('SET_ID', ''),
        commit('SET_NAME', '')

        removeToken()
        window.sessionStorage.clear()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })
        resolve()
      }).catch(error => {
        console.log(error)
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
